//
//  BMSAntiAddictionManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSAntiAddictionManager.h"
#import "BMSInitializer.h"
#import "BMSAuthManager.h"
@interface BMSAntiAddictionManager()


@end

@implementation BMSAntiAddictionManager

+ (instancetype)shared {
    static BMSAntiAddictionManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (BOOL)isTodayHoliday {
    NSString *today = [self currentDateString];
    return [self.holidaySet containsObject:today];
}

- (BOOL)isCurrentTimeInPlayWindow {
    NSDate *now = [BMSAntiAddictionManager serverTime]; // 使用服务器时间
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday | NSCalendarUnitHour fromDate:now];

    BOOL isWeekend = (comps.weekday == 6 || comps.weekday == 1 || comps.weekday == 7); // Friday, Sunday, Saturday
    BOOL isHoliday = [self isTodayHoliday];
    BOOL isAllowedTime = [self isCurrentTimeBetweenHour:20 endHour:21 usingDate:now];

    return (isHoliday || isWeekend) && isAllowedTime;
}

- (BOOL)isCurrentTimeBetweenHour:(NSInteger)startHour
                        endHour:(NSInteger)endHour
                      usingDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *nowComps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
                                                            NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
                                             fromDate:date];

    NSDateComponents *startComps = [nowComps copy];
    startComps.hour = startHour;
    startComps.minute = 0;
    startComps.second = 0;

    NSDateComponents *endComps = [nowComps copy];
    endComps.hour = endHour;
    endComps.minute = 0;
    endComps.second = 0;

    NSDate *startDate = [calendar dateFromComponents:startComps];
    NSDate *endDate = [calendar dateFromComponents:endComps];

    return ([date compare:startDate] != NSOrderedAscending &&
            [date compare:endDate] == NSOrderedAscending);
}

- (BOOL)shouldForceLogoutForTeenager {
    BOOL isTeenager = [[NSUserDefaults standardUserDefaults] boolForKey:@"bms.isTeenager"];
    if (!isTeenager) return NO;

    if (![self isCurrentTimeInPlayWindow]) {
        return YES;
    }
    return NO;
}

- (NSString *)currentDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMdd";
    return [formatter stringFromDate:[NSDate date]];
}

- (BOOL)isAllowedToPlay {
    BOOL isTeen = [BMSInitializer shared].isTeenager;
    BOOL isHoliday = [self isTodayHoliday];
    BOOL isInTimeWindow = [self isCurrentTimeInPlayWindow];

    if (!isTeen) {
        NSLog(@"[BMS] 成年人登录，无限制");
        return YES;
    }

    NSLog(@"[BMS] 未成年登录检测：节假日=%d, 时间窗口=%d", isHoliday, isInTimeWindow);
    return isInTimeWindow;
}

- (void)scheduleDailyAntiAddictionCheck {
//    [self cancelPreviousCheck]; // 确保不重复添加

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *targetComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                     fromDate:now];
    targetComponents.hour = 21;
    targetComponents.minute = 0;
    targetComponents.second = 0;

    NSDate *targetDate = [calendar dateFromComponents:targetComponents];
    if ([targetDate timeIntervalSinceNow] <= 0) {
        // 如果当前已过 21:00，设为第二天
        targetDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:targetDate options:0];
    }

    NSTimeInterval delay = [targetDate timeIntervalSinceNow];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        BOOL canPlay = [[BMSAntiAddictionManager shared] isAllowedToPlay];
        NSLog(@"[BMS] 21:00 检查防沉迷结果: %@", canPlay ? @"✅允许继续游戏" : @"❌不允许继续游戏");

        if (!canPlay) {
            [BMSAuthManager showForceExitPopup];
        }

        // 再次注册明天的检查
        [self scheduleDailyAntiAddictionCheck];
    });
}

+ (NSDate *)serverTime {
    NSString *chinaTimeStr = [[NSUserDefaults standardUserDefaults] stringForKey:@"BMS_ServerTimeOffset"];
    if (!chinaTimeStr) return [NSDate date]; // fallback：没有就用本地时间

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    return [formatter dateFromString:chinaTimeStr];
}

@end
